package com.rising.threads.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/1/7 22:36
 */
public class ShareData {

    private int number = 0;

    private Lock lock = new ReentrantLock();

    private Condition empty = lock.newCondition();
    private Condition full = lock.newCondition();

    public void producer() throws Exception {
        lock.lock();
        try {
            //只能存储1个，够1个则就停止生产
            while (number >= 1) {
                System.out.println(Thread.currentThread().getName()+"等会生产");
                full.await();
            }
            //干活 生产1个
            number++;
            System.out.println(Thread.currentThread().getName()+"生产\t" + number + "个");
            //3通知唤醒
            empty.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unlock();
        }
    }

    public void consumer() throws Exception {
        lock.lock();
        try {
            //当没有库存，则不能消费
            while (number == 0) {
                System.out.println(Thread.currentThread().getName()+"等会消费");
                empty.await();
            }
            //干活 消费1个
            number--;
            System.out.println(Thread.currentThread().getName()+"消费\t" + number+ "个");
            //3通知唤醒
            full.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unlock();
        }
    }

}
